<template>
  <Layout>
    <div class="project-detail">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        当前位置：<router-link to="/home" class="breadcrumb-link">首页</router-link> > 
        <router-link to="/volunteer-project" class="breadcrumb-link">志愿项目</router-link> > 
        <span class="breadcrumb-current">项目详情</span>
      </div>

      <!-- 项目基本信息卡片 -->
      <el-card class="detail-card">
        <div class="project-header">
          <div class="project-title">
            <h1>{{ project.activityName }}</h1>
            <el-tag 
              :type="getStatusType(project.activityStatus)"
              effect="dark"
              size="large">
              {{ getStatusLabel(project.activityStatus) }}
            </el-tag>
          </div>
          <div class="project-image">
            <el-image 
              :src="project.activityPictureInfo || '/default-project.jpg'"
              fit="cover">
              <template #error>
                <div class="image-placeholder">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </el-image>
          </div>
        </div>

        <el-descriptions class="project-info" :column="2" border>
          <el-descriptions-item label="服务类别">
            <el-tag size="small" effect="plain">{{ getServiceLabel(project.serviceCategory) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="活动地点">
            <i class="el-icon-location"></i> {{ project.address }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            <i class="el-icon-date"></i> {{ formatDate(project.startDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            <i class="el-icon-date"></i> {{ formatDate(project.endDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="活动时长">
            <i class="el-icon-time"></i> {{ project.durationDisplay }}
          </el-descriptions-item>
          <el-descriptions-item label="发布时间">
            <i class="el-icon-time"></i> {{ formatDateTime(project.publishTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="发起人">
            <i class="el-icon-user"></i> {{ project.initiator }}
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            <i class="el-icon-user"></i> {{ project.contactPerson }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <i class="el-icon-phone"></i> {{ project.contactPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="报名要求">
            <i class="el-icon-document"></i> {{ project.registrationInfo }}
          </el-descriptions-item>
          <el-descriptions-item label="志愿者保障">
            <i class="el-icon-umbrella"></i> {{ project.volunteerProtectionInfo }}
          </el-descriptions-item>
          <el-descriptions-item label="招募人数" :span="2">
            <el-progress 
              :percentage="(project.registeredNumber / project.recruitmentNumber) * 100"
              :format="() => `${project.registeredNumber}/${project.recruitmentNumber}人`"
              :status="project.registeredNumber >= project.recruitmentNumber ? 'success' : ''"
            />
          </el-descriptions-item>
        </el-descriptions>

        <div class="project-description">
          <h2>活动详情</h2>
          <div class="description-content">{{ project.details }}</div>
        </div>

        <div class="action-buttons">
          <el-button 
            type="primary" 
            size="large"
            :disabled="project.activityStatus === '1' || project.activityStatus === '3'"
            @click="handleJoin">
            {{ isRegistered ? '已报名' : '立即报名' }}
          </el-button>
          <el-button 
            type="default" 
            size="large"
            @click="router.push('/volunteer-project')">
            返回列表
          </el-button>
        </div>
      </el-card>
    </div>
  </Layout>
</template>

<script setup>
import Layout from '@/components/Layout.vue'
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const project = ref({})
const isRegistered = ref(false)

// 获取项目详情
const fetchProjectDetail = async () => {
  try {
    const response = await axios.get(`http://localhost:9090/activities/${route.params.id}`)
    project.value = response.data
  
    // 检查是否已报名
    const volunteerId = localStorage.getItem('volunteerId')
    if(volunteerId) {
      const registrationResponse = await axios.get(`http://localhost:9090/registrations/check`, {
        params: {
          activityId: route.params.id,
          volunteerId: volunteerId
        }
      })
      isRegistered.value = registrationResponse.data || false
    }
  } catch (error) {
    ElMessage.error('获取项目详情失败')
    console.error('获取项目详情失败:', error)
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  const date = new Date(dateStr)
  return `${formatDate(dateStr)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取服务类别标签
const getServiceLabel = (value) => {
  const services = [
    { value: '1', label: '社区服务' },
    { value: '2', label: '文化艺术' },
    { value: '3', label: '义务维修' },
    { value: '4', label: '环境保护' },
    { value: '5', label: '交通引导' },
    { value: '6', label: '禁毒宣传' },
    { value: '7', label: '其他' }
  ]
  const service = services.find(s => s.value === value)
  return service ? service.label : ''
}

// 获取状态标签
const getStatusLabel = (value) => {
  const statuses = [
    { value: '1', label: '待开始' },
    { value: '2', label: '进行中' },
    { value: '3', label: '已结束' }
  ]
  const status = statuses.find(s => s.value === value)
  return status ? status.label : ''
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '1': return 'warning'  // 待开始
    case '2': return 'success'  // 进行中
    case '3': return 'info'     // 已结束
    default: return ''
  }
}

// 是否可以报名
const canJoin = computed(() => {
  return project.value.activityStatus === '2' && 
         project.value.registeredNumber < project.recruitmentNumber &&
         !isRegistered.value
})

// 处理报名
const handleJoin = async () => {
  if(localStorage.getItem('type') === null) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }

  if(localStorage.getItem('type') === 'admin') {
    ElMessage.error('当前账号为管理员，无法报名志愿者活动，请切换账号再进行操作！')
    return
  }
  
  if(isRegistered.value) {
    ElMessage.info('您已报名该活动')
    return
  }

  try {
    // 重新获取最新的项目信息，确保数据是最新的
    const latestProjectResponse = await axios.get(`http://localhost:9090/activities/${route.params.id}`)
    const latestProject = latestProjectResponse.data

    // 检查是否已经满员
    if (latestProject.registeredNumber >= latestProject.recruitmentNumber) {
      ElMessage.error('抱歉，该项目已经满员')
      await fetchProjectDetail() // 刷新页面数据
      return
    }
    
    const registration = {
      activityId: parseInt(route.params.id),
      volunteerId: parseInt(localStorage.getItem('volunteerId')),
      status: '已报名',
      remarks: ''
    }
    
    // 先创建报名记录
    const registrationResponse = await axios.post('http://localhost:9090/registrations', registration)

    if(registrationResponse.data) {
      // 更新活动报名人数
      const activityId = parseInt(route.params.id)
      const updateResponse = await axios.put(`http://localhost:9090/activities/${activityId}`, {
        activityId: activityId,
        registeredNumber: latestProject.registeredNumber + 1
      })
      
      if(updateResponse.data) {
        ElMessage.success('报名成功')
        isRegistered.value = true
        fetchProjectDetail()
      } else {
        // 如果更新失败，需要回滚报名记录
        await axios.delete(`http://localhost:9090/registrations/${registrationResponse.data.id}`)
        ElMessage.error('报名失败，请稍后重试')
      }
    } else {
      ElMessage.error('此项目为组织招募，您不属于该组织，请联系相关责任人')
    }
  } catch (error) {
    ElMessage.error('报名失败，请稍后重试')
    console.error('报名失败:', error)
  }
}

onMounted(() => {
  fetchProjectDetail()
})
</script>

<style scoped>
.project-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  color: #666;
  font-size: 14px;
}

.breadcrumb-link {
  color: #dd2b2b;
  text-decoration: none;
}

.breadcrumb-link:hover {
  color: #ff4d4d;
}

.breadcrumb-current {
  color: #dd2b2b;
}

.detail-card {
  margin-bottom: 20px;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
}

.project-title {
  flex: 1;
}

.project-title h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.project-image {
  width: 300px;
  height: 200px;
  margin-left: 20px;
}

.project-image .el-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 30px;
}

.project-info {
  margin: 20px 0;
}

.project-description {
  margin: 30px 0;
}

.project-description h2 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.description-content {
  line-height: 1.6;
  color: #666;
  white-space: pre-wrap;
}

.action-buttons {
  text-align: center;
  margin-top: 30px;
}

.action-buttons .el-button {
  margin: 0 10px;
  min-width: 120px;
}
</style>
